
package es.ceu.mp2.conway;

//import com.sun.xml.internal.ws.message.source.PayloadSourceMessage;


public class Game {
    private GameBoard actualBoard;
    private ConwayGUI gameGUI;
    private int maxIterations;
    boolean playPressedNextStepNot;

    public void executeGameOfLife(String gameName, int iterations, String initialGameFile){
        Reader reader = new ReaderFactory().getReader(initialGameFile);
        actualBoard = reader.read(initialGameFile);
        gameGUI = new ConwayGUI(actualBoard, iterations, gameName);
        maxIterations = iterations;
        int i = 0;

        actualBoard.printTable(gameGUI);
        playPressedNextStepNot = gameGUI.pause();  

        while(i < maxIterations){
            if (playPressedNextStepNot)
                i = executeIterations(i);

            else{
                executeSimpleStep();
                i++;
                gameGUI.setIterations(i);
                playPressedNextStepNot = gameGUI.pause();
            }
        }
    }

    private int executeIterations(int i) {
        boolean paused;

        for (; i < maxIterations; i++){
            actualBoard.nextIteration();
            paused = actualBoard.printTable(gameGUI);
            if (paused){
                playPressedNextStepNot = gameGUI.pause();
                return i;
            }
            gameGUI.setIterations(i+1);
            try {
                Thread.sleep((100 - gameGUI.getSpeed())*4);
            } catch (InterruptedException ex) {
                System.out.println(ex);
            }
        }
        return i;
    }

    private boolean executeSimpleStep() {
        actualBoard.nextIteration();
        boolean paused = actualBoard.printTable(gameGUI);
            if (paused)
                playPressedNextStepNot = gameGUI.pause();
        return paused;
    }

}
